import { LoginEnt } from '@/models/LoginEnt';
import { b64_decode, b64_encode } from '@/utils/codeUtils';
import type { CaseReducer, PayloadAction } from '@reduxjs/toolkit';
import { createSlice } from '@reduxjs/toolkit';

const LOGINENTSTOREKEY = window.__POWERED_BY_QIANKUN__ ? 'safeEduMicroLoginEnt' : 'safeEduLoginEnt';

const loginEntSlice = createSlice<
  LoginEnt,
  {
    updateLoginEnt: CaseReducer<LoginEnt, PayloadAction<LoginEnt | undefined>>;
  },
  'loginEnt'
>({
  name: 'loginEnt',
  initialState: () => {
    const initialState = new LoginEnt();
    const loginEntSecret = localStorage.getItem(LOGINENTSTOREKEY);
    if (loginEntSecret) {
      try {
        Object.assign(initialState, JSON.parse(b64_decode(loginEntSecret)));
      } catch (err) {
        console.log('--LoginEntSlice--err-loginEnt--:', err);
      }
    }
    return initialState;
  },
  reducers: {
    updateLoginEnt: (state, { payload = new LoginEnt() }) => {
      localStorage.setItem(LOGINENTSTOREKEY, b64_encode(JSON.stringify(payload)));
      return { ...payload };
    },
  },
});
export { loginEntSlice };
